<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use App\Models\Video;
use Rainsens\Dinglog\Facades\Dinglog;

class VideosReturnController extends Controller
{
	public function ghostcutReturn()
	{
		$body = request()->all();

		Log::debug(json_encode($body));

		$content=$body;
		$name=$content['name'];

		$projectId = $content['idProject'];


		$video = Video::query()->where("ghost_project_id",$projectId)->first();

		if(isset($content['videoUrl'])){

			if($content['srcSrtUrl']){

				$srt = file_get_contents($content['srcSrtUrl']);

				$brief = $this->briefCreate($srt);


			}
			$updateData = [
				'title_en'=>$this->useGptTranslate($video->title),
				"brief"=>$brief,
				'brief_en'=>$this->useGptTranslate($brief),
				'translate_video_url'=>$content['videoUrl'],
				'srt_url'=>$content['srcSrtUrl']
			];
			
			
			$video->update($updateData);
			return response()->json(['msg'=>"success","code"=>200],200);
		}
		

		
		
	}

	 public function useGptTranslate($text){
		$content = [
		    'model' => 'gpt-3.5-turbo',
		    'messages' => [
		    	['role' => 'system', "content"=> "你是个翻译工作者,将下方内容翻译成英文"],
		        ['role' => 'user', 'content' => $text],
		    ]
		];
		$content = $this->curl($content);
		$content = json_decode($content,true);

		return  $content['choices'][0]['message']['content'];

    }

	public function briefCreate($content){

		$titleContent = [
		    'model' => "gpt-3.5-turbo",
		     'messages' => [
		    	['role' => 'system', "content"=> cs()->videos_brief_prompt],
		        ['role' => 'user', 'content' => $content],

		    ],
		    
		]; 

		$titleResult = $this->curl($titleContent);
		
		$titleResult = json_decode($titleResult,true);
		return  $titleResult['choices'][0]['message']['content'];

    }


    public function curl($data){

		$curl = curl_init();
		$data = json_encode($data);


		curl_setopt_array($curl, array(
		   CURLOPT_URL => 'https://api.chatanywhere.tech/v1/chat/completions',
		   CURLOPT_RETURNTRANSFER => true,
		   CURLOPT_ENCODING => '',
		   CURLOPT_MAXREDIRS => 10,
		   CURLOPT_TIMEOUT => 0,
		   CURLOPT_FOLLOWLOCATION => true,
		   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		   CURLOPT_CUSTOMREQUEST => 'POST',
		   CURLOPT_POSTFIELDS =>$data,
		   CURLOPT_HTTPHEADER => array(
		      'Authorization: Bearer '.env('CHATGPT_API_KEY'),
		      'User-Agent: Apifox/1.0.0 (https://apifox.com)',
		      'Content-Type: application/json'
		   ),
		));

	   $response = curl_exec($curl);

	   
	   return $response;
	}
	
	
}
